package com.briup.bookstore.service.impl;

import com.briup.bookstore.common.exception.ServiceException;
import com.briup.bookstore.common.response.ResultCode;
import com.briup.bookstore.common.security.SecurityContext;
import com.briup.bookstore.domain.bean.Book;
import com.briup.bookstore.domain.bean.Shopcar;
import com.briup.bookstore.domain.vo.BookShopCarDetailVO;
import com.briup.bookstore.mapper.BookMapper;
import com.briup.bookstore.mapper.ShopcarMapper;
import com.briup.bookstore.service.ShopcarService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ShopcarServiceImpl implements ShopcarService {

    private final ShopcarMapper shopcarMapper;
    private final BookMapper bookMapper;

    @Override
    public List<BookShopCarDetailVO> listByUserId() {
        // 获取当前登录用户的id
        Integer userId = SecurityContext.userId();
        // 查询用户购物车中的书籍详情
        return shopcarMapper.listByUserId(userId);
    }

    @Override
    public void addBookToShopcar(Integer bookId, Integer num) {
        // 获取当前用户的id
        Integer userId = SecurityContext.userId();
        // 校验该图书是否存在
        Book book = bookMapper.queryById(bookId, null);
        if (book == null) {
            throw new ServiceException(ResultCode.BOOK_IS_NOT_EXISTS);
        }
        // 图书存在的情况下，直接将图书添加到购物车中
        // 在此之前先确定购物车中是否存在该图书
        Shopcar shopcar = shopcarMapper.queryByUserIdAndBookId(userId, bookId);
        if (shopcar == null) {
            // 购物车中不存在该图书，直接新增即可
            shopcar = new Shopcar();
            shopcar.setBookId(bookId);
            shopcar.setUserId(userId);
            shopcar.setNum(num);
        } else {
            // 购物车中已存在该图书，直接更新数量即可
            shopcar.setNum(shopcar.getNum() + num);
        }
        // 最后将购物车数据保存到数据库中
        shopcarMapper.insertOrUpdate(shopcar);
    }

    @Override
    public void updateShopcarNum(Integer id, Integer num) {
        shopcarMapper.updateShopcarNum(id, num);
    }

    @Override
    public void deleteShopcarItem(List<Integer> ids) {
        Integer userId = SecurityContext.userId();
        shopcarMapper.deleteShopcarItem(ids, userId);
    }
}
